﻿using System;
using System.Web.UI;
using System.ComponentModel;
using System.Security.Permissions;
using System.Web;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections;

namespace Basic4Net.Controls
{
	[
	  AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal),
	  AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal),
	  ToolboxData("<{0}:BNGridView runat=\"server\"> </{0}:BNGridView>")
   ]

	public class BNGridView : GridView
	{
		#region Property

		//private const string NO_RESULTS = "Sorry, no results were found for your search.";

		[Category("Custom")]
		[Browsable(true)]
		[Description("始终显示表头")]
		[DefaultValue(true)]
		public bool ShowHeaderAllways
		{
			get
			{
				object obj = ViewState["ShowHeaderAllways"];
				if (obj != null)
					return (bool)obj;

				return true;
			}
			set { ViewState["ShowHeaderAllways"] = value; }
		}

		[Category("Customer"),
		Browsable(true),
		Description("Position of SeqNo"),
		DefaultValue("0")
		]
		public int SeqNo
		{
			get
			{
				return (ViewState["SeqNo"] != null) ? (int)ViewState["SeqNo"] : 0;
			}
			set
			{
				ViewState["SeqNo"] = value;
			}
		}

		[Category("Customer"),
		Browsable(true),
		Description("Name of SeqNo")
		]
		public string SeqText
		{
			get
			{
				return (ViewState["SeqText"] != null) ? (string)ViewState["SeqText"] : "NO.";
			}
			set
			{
				ViewState["SeqText"] = value;
			}
		}



		[Category("Customer"),
		Browsable(true),
		Description("Does SeqNo show"),
		DefaultValue(false)
		]
		public bool ShowSeqNo
		{
			get
			{
				return (ViewState["ShowSeqNo"] != null) ? (bool)ViewState["ShowSeqNo"] : false;
			}
			set
			{
				ViewState["ShowSeqNo"] = value;
			}
		}

		[Category("Customer"),
		Browsable(true),
		Description("ID of pager control")]
		public string PagerID
		{
			get
			{
				return (ViewState["_GridPagerID"] != null) ? ViewState["_GridPagerID"].ToString() : "GridPager1";
			}
			set
			{
				ViewState["_GridPagerID"] = value;
			}
		}

		private string _CssClass = "Grid_General";
		[Category("Customer"),
		 Browsable(true),
		 Description("Name of CssClass"),
		 DefaultValue("Grid_General")
		]
		public override string CssClass
		{
			get
			{
				return this._CssClass;
			}
			set
			{
				this._CssClass = value;
			}
		}

		private bool _AllowPaging = true;
		[Category("Customer"),
		 Browsable(true),
		 Description("Does paging function open"),
		DefaultValue(true)
		]
		public override bool AllowPaging
		{
			get
			{
				return this._AllowPaging;
			}
			set
			{
				this._AllowPaging = value;
			}
		}

		private bool _AutoGenerateColumns = false;
		[Category("Customer"),
		Browsable(true),
		Description("AutoGenerationColumns"),
		DefaultValue(false)
		]
		public override bool AutoGenerateColumns
		{
			get
			{
				return this._AutoGenerateColumns;
			}
			set
			{
				this._AutoGenerateColumns = value;
			}
		}

		private string _SNWidth = "5%";
		[Category("Customer"),
		Browsable(true),
		Description("Width of SeqNo column"),
		DefaultValue("5%")
		]
		public string SNWidth
		{
			get
			{
				return this._SNWidth;
			}
			set
			{
				this._SNWidth = value;
			}
		}

		private bool _PagerVisible = false;
		[Category("Customer"),
		Browsable(true),
		Description("PagerVisible"),
		DefaultValue(false)
		]
		public bool PagerVisible
		{
			get
			{
				return this._PagerVisible;
			}
			set
			{
				this._PagerVisible = value;
			}
		}

		#endregion

		//public CustGridView()
		//{
		//    this.init();
		//    this.Init += new EventHandler(CustGridView_Init);
		//}

		//protected void init()
		//{
		//    this.CssClass = "Grid_General";
		//    this.HeaderStyle.CssClass = "Grid_Header";
		//    //this.ItemStyle.CssClass = "Grid_Item";
		//    //this.AlternatingItemStyle.CssClass = "Grid_AlternatingItem";
		//    //this.SelectedItemStyle.CssClass = "Grid_SelectedItem";
		//    this.AllowPaging = true;
		//    this.PagerStyle.CssClass = "Grid_Pager";
		//    this.AutoGenerateColumns = false;
		//}

		private void CustGridView_RowDataBound(object sender, GridViewRowEventArgs e)
		{

			if (e.Row.RowIndex > -1)
			{
				if (e.Row.RowType == DataControlRowType.DataRow)
				{
					int pageSize = this.PageSize;
					int pageIndex = this.PageIndex;
					if (this.PagerID != null && this.PagerID != "")
					{
						BNPager pager = (BNPager)this.Parent.FindControl(this.PagerID);
						if (pager != null)
						{
							pageSize = pager.PageSize;
							pageIndex = pager.PageIndex - 1;
							this.PageSize = pageSize;
							if (pageIndex * pageSize > pager.RecordCount)
							{
								pageIndex = pageIndex - 1;
							}
						}
					}
					int i = pageSize * pageIndex + e.Row.RowIndex + 1;
					e.Row.Cells[this.SeqNo].Text = i.ToString();
				}
			}
		}

		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);
			//this.CssClass = "Grid_General";
			this.Attributes.Add("class", this.CssClass);
			this.HeaderStyle.Wrap = false;
			this.HeaderStyle.CssClass = "Grid_Header A";
			this.RowStyle.CssClass = "Grid_Item";
			this.AlternatingRowStyle.CssClass = "Grid_AlternatingItem";
			this.SelectedRowStyle.CssClass = "Grid_SelectedItem";
			this.BorderStyle = BorderStyle.Solid;
			//this.AllowPaging = true;
			//this.PagerStyle.CssClass = "Grid_Pager";
			this.PagerSettings.Visible = this._PagerVisible;
			//try
			//{
			//    bHaved = (this.Columns[this.SeqNo].HeaderText == this.SeqText);
			//}
			//catch(Exception ex)
			//{
			//    TraceContext objTC = new TraceContext(HttpContext.Current);
			//    ISS.Procuro.SysFrameWork.Logger logger = new ISS.Procuro.SysFrameWork.Logger(ref objTC);
			//    logger.Log(ref ex);

			//}
			bool bHaved = false;
			if (this.Columns.Count > 0)
			{
				bHaved = (this.Columns[this.SeqNo].HeaderText == this.SeqText);
			}
			else
			{
				return;
			}
			if (ShowSeqNo)
			{
				if (!bHaved)//Generate SeqNo column
				{
					BoundField bf = new BoundField();
					bf.HeaderText = this.SeqText;
					bf.HeaderStyle.Width = new Unit(this._SNWidth);
					bf.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
					bf.HeaderStyle.Wrap = false;
					bf.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
					bf.ItemStyle.Wrap = false;
					bf.ReadOnly = true;

					this.Columns.Insert(this.SeqNo, bf);
				}
				this.RowDataBound += new GridViewRowEventHandler(CustGridView_RowDataBound);
			}
			else
			{
				if (bHaved)
				{
					this.Columns.RemoveAt(this.SeqNo);
				}
			}
			//base.OnInit(e);
		}
		//private void CustGridView_Init(object sender, EventArgs e)
		//{

		//}

		protected override void OnPreRender(EventArgs e)
		{
			base.OnPreRender(e);

			this.CreateHeaderRow();
		}

		private void CreateHeaderRow()
		{
			if (ShowHeaderAllways)
			{
				Table maintable = null;
				if (this.Controls.Count == 0)
				{
					maintable = new Table();
					maintable.ApplyStyle(this.ControlStyle);
					this.Controls.Add(maintable);
				}
				else
					maintable = this.Controls[0] as Table;

				bool IsCreateHeader = false;

				bool IsCreateEmptyRow = false;

				if (maintable.Rows.Count == 0)
				{
					IsCreateHeader = true;
					IsCreateEmptyRow = true;
				}
				else
				{
					GridViewRow gvr = maintable.Rows[0] as GridViewRow;
					if (gvr.RowType == DataControlRowType.EmptyDataRow)
					{
						maintable.Rows.Clear();
						IsCreateHeader = true;
						IsCreateEmptyRow = true;
					}
					else
					{
						IsCreateHeader = false;
						IsCreateEmptyRow = false;
					}
				}

				int ColumnCount = 0;

				if (IsCreateHeader)
				{
					GridViewRow gvr = new GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Normal);
					gvr.ApplyStyle(this.HeaderStyle);
					for (int i = 0; i < this.Columns.Count; i++)
					{
						DataControlField column = this.Columns[i];

						if (column.ShowHeader)
						{
							ColumnCount++;

							DataControlFieldHeaderCell tc = new DataControlFieldHeaderCell(column);
							tc.ApplyStyle(column.HeaderStyle);
							column.InitializeCell(tc, DataControlCellType.Header, DataControlRowState.Normal, 0);

							gvr.Cells.Add(tc);
						}
					}
					maintable.Rows.AddAt(0, gvr);
				}

				if (IsCreateEmptyRow)
				{
					if (this.EmptyDataText != string.Empty)
					{
						GridViewRow gvr = new GridViewRow(0, 0, DataControlRowType.EmptyDataRow, DataControlRowState.Normal);
						gvr.ApplyStyle(this.EmptyDataRowStyle);
						TableCell tc = new TableCell();
						tc.Text = this.EmptyDataText;
						tc.ColumnSpan = ColumnCount;

						gvr.Cells.Add(tc);

						maintable.Rows.Add(gvr);
					}
				}
			}
		}

		#region Old DataBind Code
		//public new void DataBind()
		//{
		//    if (this.DataSource is DataSet)
		//    {
		//        DataSet ds = (DataSet)this.DataSource;
		//        if (ds.Tables[0].Rows.Count == 0)
		//        {
		//            ds.EnforceConstraints = false;
		//            DataTable dt = ds.Tables[0];
		//            dt.Rows.Add(dt.NewRow());
		//            base.DataBind();
		//            this.Rows[0].Visible = false;
		//        }
		//        else
		//        {
		//            base.DataBind();
		//        }
		//    }
		//    else if (this.DataSource is DataView)
		//    {
		//        DataView dv = (DataView)this.DataSource;
		//        if (dv.Count == 0)
		//        {
		//            dv.AddNew();
		//            base.DataBind();
		//            this.Rows[0].Visible = false;
		//        }
		//        else
		//        {
		//            base.DataBind();
		//        }
		//    }
		//    else if (this.DataSource is DataTable)
		//    {
		//        DataTable dt = (DataTable)this.DataSource;
		//        if (dt.Rows.Count == 0)
		//        {
		//            dt.DataSet.EnforceConstraints = false;
		//            DataRow dr = dt.NewRow();
		//            dt.Rows.Add(dr);
		//            base.DataBind();
		//            this.Rows[0].Visible = false;
		//        }
		//        else
		//        {
		//            base.DataBind();
		//        }
		//    }            
		//    else if (this.DataSource is ArrayList)
		//    {
		//        ArrayList al = (ArrayList)this.DataSource;
		//        if (al.Count == 0)
		//        {

		//            //al.Add(NO_RESULTS);
		//            //al.Add(obj);

		//            base.DataBind();
		//        }
		//        else
		//        {
		//            base.DataBind();
		//        }
		//    }
		//    else if (this.DataSource is Hashtable)
		//    {
		//        Hashtable ht = (Hashtable)this.DataSource;
		//        if (ht.Count == 0)
		//        {
		//            ht.Add("", "");
		//            base.DataBind();
		//        }
		//        else
		//        {
		//            base.DataBind();
		//        }
		//    }
		//    else
		//    {
		//        base.DataBind();
		//    }
		//}
		#endregion
	}
}
